package com.dd.logistics.utils;

import com.dd.logistics.config.UploadConfig;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Component
@Slf4j
public class FileUploadUtil {
    
    @Autowired
    private UploadConfig uploadConfig;
    
    public String uploadImage(MultipartFile file) throws IOException {
        try {
            log.info("开始上传图片：{}", file.getOriginalFilename());
            
            // 验证图片
            ImageValidateUtil.validateImage(file);
            
            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            String filename = UUID.randomUUID().toString() + extension;
            
            // 创建目录
            String datePath = DateUtil.format(new Date(), "yyyy/MM/dd");
            String fullPath = uploadConfig.getBasePath() + datePath;
            File directory = new File(fullPath);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            
            // 保存文件
            File destFile = new File(directory, filename);
            file.transferTo(destFile);
            
            // 返回完整的URL（使用配置的baseUrl）
            String url = uploadConfig.getBaseUrl() + datePath + "/" + filename;
            log.info("图片上传成功，URL：{}", url);
            return url;
            
        } catch (Exception e) {
            log.error("图片上传失败：{}", e.getMessage());
            throw new RuntimeException("图片上传失败：" + e.getMessage());
        }
    }
    
    public void deleteImage(String imageUrl) {
        if (imageUrl == null || imageUrl.trim().isEmpty()) {
            return;
        }
        try {
            // 从URL中提取文件路径
            String baseUrl = uploadConfig.getBaseUrl();
            String relativePath = imageUrl.substring(baseUrl.length());
            String fullPath = uploadConfig.getBasePath() + relativePath;
            File file = new File(fullPath);
            
            if (file.exists() && file.isFile()) {
                if (!file.delete()) {
                    log.warn("删除文件失败：{}", imageUrl);
                } else {
                    log.info("删除文件成功：{}", imageUrl);
                }
            }
        } catch (Exception e) {
            log.error("删除文件异常：{}", e.getMessage());
        }
    }
} 